<template>
  <scroll-view 
    class="page-container" 
    scroll-y="true" 
    refresher-enabled="true"
    :refresher-triggered="isRefreshing"
    @refresherrefresh="onRefresh"
    refresher-background="#f5f5f5"
  >
    <!-- 用户信息部分 -->
    <view class="box">
     <navigator class="user-info" url="/subPackages/modifyInfo/modifyInfo">
      <image class="avatar" :src="userInfor.avatar" mode="aspectFill"></image>
      <view class="user-detail">
        <view class="username">{{ userInfor.username }} </view>
        <text class="user-type">{{ userType }}</text>
      </view>
      <view class="arrow">></view>
     </navigator>
     </view>
    <!-- 功能列表部分 -->
    <view class="function-list">
      <navigator class="function-item" v-for="(item, index) in functionItems" :key="index" :url="item.url">
        <view class="left">
          <image class="icon" :src="item.icon"></image>
          <text class="item-text">{{ item.text }}</text>
        </view>
       <view class="right">
         <text v-if="item.desc" class="desc-text">{{ item.desc }}</text>
         <text class="arrow">></text>
       </view>
      </navigator>
    </view>

    <!-- 分享按钮部分 -->
    <view class="lagout-btn">
      <button class="btn lagout" @click="showLagout=true">退出登录</button>
    </view>
    <view class="share-btn">
      <button class="btn share" open-type="share">分享给朋友</button>
    </view>

    <!-- 底部说明部分 -->
    <view class="bottom-info">
      <text>面试鸭网页刷题:mianshiya.com</text>
      <text>JetBrains IDE 刷题插件</text>
      <text>我已阅读并同意<text class="link" @click="goToProtocol">《用户协议》</text>及<text class="link" @click="goToPrivacy">《隐私政策》</text></text>
    </view>
  </scroll-view>
  <view v-if="showLagout" class="lagout-dialog-overlay" @click.stop="cancellagout"></view>
  <view v-if="showLagout" class="lagout-dialog">
    <view class="lagout-dialog-content">
      <view class="lagout-dialog-title">提示</view>
      <view class="lagout-dialog-message">确定退出登录吗?</view>
      <view class="lagout-dialog-buttons">
        <button class="cancel-button" @click="showLagout=false">取消</button>
        <button class="confirm-button" @click="confirmLagout">确定</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
// 分享到朋友
onShareAppMessage(() => {
  return {
    title: '面试宝典 - 程序员面试刷题神器',
    path: '/pages/index/index',
    imageUrl: '/static/share-image.png', 
    success: function(res) {
      uni.showToast({
        title: '分享成功',
        icon: 'success'
      });
    },
    fail: function(err) {
      console.error('分享失败', err);
    }
  };
});

// 分享到朋友圈
onShareTimeline(() => {
  return {
    title: '面试鸭 - 程序员面试刷题神器',
    query: '',
    imageUrl: '/static/share-image.png' 
  };
});

// 下拉刷新状态
const isRefreshing = ref(false);

// 下拉刷新处理函数
const onRefresh = async () => {
  isRefreshing.value = true;
  try {
    // 刷新用户信息
    await getUserInfo();
    
    // 显示刷新成功提示
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000
    });
  } catch (error) {
    console.error('刷新数据失败:', error);
    uni.showToast({
      title: '刷新失败',
      icon: 'none',
      duration: 1000
    });
  } finally {
    // 无论成功失败，都结束刷新状态
    setTimeout(() => {
      isRefreshing.value = false;
    }, 1000);
  }
};

//退出登录
const showLagout=ref(false);
const cancellagout = () => {
  showLagout.value = false;
};
const confirmLagout=()=>{
  // 清除存储的token和其他用户信息
  uni.removeStorageSync('token');
  uni.removeStorageSync('userInfo');
  uni.removeStorageSync('userInfor');
  
  // 跳转到登录页
  redirectToLogin();
};
const redirectToLogin = () => {
  // 获取当前页面路径，用于登录后可能的重定向
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const currentRoute = currentPage ? currentPage.route : '';
  
  // 如果当前已经在登录页，则不再跳转
  if (currentRoute.includes('login')) {
    return;
  }
  
  // 关闭所有页面，打开登录页
  uni.reLaunch({
    url: '/pages/login/login'
  });
};
// 用户信息
const userInfor = reactive({
  avatar: '',
  username: ''
});

const userType = ref('普通用户');

// 更新本地用户信息的函数
const updateLocalUserInfo = (data) => {
  if (data.username) {
    userInfor.username = data.username;
  }

  if (data.avatar) {
    // 检查头像URL是否已包含基础URL
    if (data.avatar.startsWith('http')) {
      userInfor.avatar = data.avatar;
    } else {
      userInfor.avatar = "https://www.liujie.cyou/" + data.avatar;
    }
  }
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await uni.$http.get('/api/v1/users');
    if (res.data && res.data.code === 200) {
      const userData = res.data.data;

      // 处理头像URL
      let avatarUrl = userData.avatar;
      if (avatarUrl && !avatarUrl.startsWith('http')) {
        avatarUrl = "https://www.liujie.cyou/" + avatarUrl;
      }

      // 更新本地数据
      userInfor.avatar = avatarUrl;
      userInfor.username = userData.username;

      // 保存到本地存储
      uni.setStorageSync('userInfor', JSON.stringify({
        id: userData.id,
        avatar: avatarUrl,
        username: userData.username
      }));
      
      return true;
    }
    return false;
  } catch (err) {
    console.error('获取用户信息失败', err);
    uni.showToast({
      title: "获取数据失败",
      icon: 'none'
    });
    throw err;
  }
};

// 用户信息更新事件处理函数
const handleUserInfoUpdated = (data) => {
  updateLocalUserInfo(data);
};

// 页面加载时获取用户信息
onMounted(() => {
  getUserInfo();
  
  // 添加用户信息更新事件监听
  uni.$on('userInfoUpdated', handleUserInfoUpdated);
});

// 页面显示时更新用户信息
onShow(() => {
  // 从本地存储获取最新的用户信息
  const storedUserInfo = uni.getStorageSync('userInfor');
  if (storedUserInfo) {
    try {
      const parsedInfo = JSON.parse(storedUserInfo);
      updateLocalUserInfo(parsedInfo);
    } catch (e) {
      console.error('解析用户信息失败', e);
    }
  }
});

// 页面卸载前移除事件监听
onBeforeUnmount(() => {
  uni.$off('userInfoUpdated', handleUserInfoUpdated);
});

// 功能列表
const functionItems = ref([
  {
    icon: '/static/icons/1.png', 
    text: '会员',
    desc: '畅刷所有题目 + 获取上百场模拟面试视频',
    url: '' 
  },
  {
    icon: '/static/icons/2.png', 
    text: '点击兑换',
    url: '' 
  },
  {
    icon: '/static/icons/3.png', 
    text: '回答收藏',
    url: '/subPackages/answer-collect/answer-collect' 
  },
  {
    icon: '/static/icons/4.png', 
    text: '题目收藏',
    url: '/subPackages/question-collect/question-collect' 
  },
  {
    icon: '/static/icons/5.png', 
    text: '刷题记录',
    url: '/subPackages/practice-record/practice-record' 
  },
  {
    icon: '/static/icons/6.png', 
    text: '我的回答',
    url: '/subPackages/my-answers/my-answers' 
  },
  {
    icon: '/static/icons/7.png', 
    text: '刷题设置',
    url: '' 
  }
]);

// 跳转到用��协议页面
const goToProtocol = () => {
  uni.navigateTo({
    url: '/pages/agreement/user-agreement'
  });
};

// 跳转到隐私政策页面
const goToPrivacy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacy-policy'
  });
};
</script>

<style scoped lang="scss">
.page-container {
  background-color: #fff;
  height: 100vh;
  
  .box{
    height: 150rpx;
    border-bottom: 20rpx solid #e5e5e5;
    .user-info {
      display: flex;
      align-items: center;
      padding: 20rpx;
      .avatar {
        width: 110rpx;
        height: 110rpx;
        margin-right: 20rpx;
        border-radius: 50%;
      }
      .user-detail {
        flex: 1;
        .username {
          font-size: 32rpx;
          font-weight: bold;
        }
        .user-type {
          font-size: 28rpx;
          color: #999;
        }
      }
    }
  }

.arrow {
  font-size: 65rpx !important;
  color: #cccccc;
}

.function-list {
  padding: 0 20rpx;
  .function-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #e5e5e5;
    .left{
      display: flex;
      align-items: center;
      .icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 20rpx;
      }
      .item-text {
        font-size: 30rpx;
      }
    }
    .right {
      display: flex;
      align-items: center;
      font-size: 20rpx;
      color: #999;
      
      .desc-text {
        margin-right: 10rpx;
        max-width: 400rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
.function-item:last-child {
      border-bottom: none;
    }
.lagout-btn{
  margin-top: 40rpx;
  text-align: center;
}

.share-btn {
  margin: 40rpx 0;
  text-align: center;
}

.btn {
  width: 80%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #ffc500;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
  &.lagout{
    background-color: red;
  }
  &.share {
    background-color: #07c160;
  }
}

.bottom-info {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  padding: 30rpx 0 50rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.link {
  color: #007aff;
}
}
  .lagout-dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1002;
  }
  
  .lagout-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    max-width: 600rpx;
    background-color: #fff;
    border-radius: 10rpx;
    z-index: 1003;
    overflow: hidden;
    
    .lagout-dialog-content {
      padding: 30rpx;
      
      .lagout-dialog-title {
        font-size: 32rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 20rpx;
      }
      
      .lagout-dialog-message {
        font-size: 28rpx;
        text-align: center;
        margin-bottom: 30rpx;
      }
      
      .lagout-dialog-buttons {
        display: flex;
        border-top: 1rpx solid #eee;
        margin: 0 -30rpx -30rpx;
        
        button {
          flex: 1;
          border: none;
          background: none;
          font-size: 28rpx;
          padding: 20rpx 0;
          
          &.cancel-button {
            color: #666;
            border-right: 1rpx solid #eee;
          }
          
          &.confirm-button {
            color: #ff3b30;
          }
        }
      }
    }
  }
</style>